package com.example.getaudit.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.getaudit.common.enums.BanMaHuiEnum;
import com.example.getaudit.entity.CommodityMarketPriceMonthly;
import com.example.getaudit.entity.VToMsyBcd;
import com.example.getaudit.mapper.CommodityMarketPriceMonthlyDao;
import com.example.getaudit.request.BanMaHuiRequest;
import com.example.getaudit.service.CommodityMarketPriceMonthlyService;
import com.example.getaudit.service.VToMsyBcdService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

import static cn.hutool.crypto.SecureUtil.md5;

/**
 * 商品区域参考价月表 服务实现类
 *
 * @author 
 * @since 2025/03/18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CommodityMarketPriceMonthlyServiceImpl extends ServiceImpl<CommodityMarketPriceMonthlyDao,CommodityMarketPriceMonthly> implements CommodityMarketPriceMonthlyService {

    private final CommodityMarketPriceMonthlyDao commodityMarketPriceMonthlyDao;
    @Resource
    VToMsyBcdService vToMsyBcdService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(CommodityMarketPriceMonthly commodityMarketPriceMonthly ) {
        commodityMarketPriceMonthlyDao.insert(commodityMarketPriceMonthly);
        return Long.valueOf(commodityMarketPriceMonthly.getId());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CommodityMarketPriceMonthly commodityMarketPriceMonthly) {
        commodityMarketPriceMonthlyDao.updateById(commodityMarketPriceMonthly);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        commodityMarketPriceMonthlyDao.deleteById(id);
    }

    @Override
    public CommodityMarketPriceMonthly get(Long id) {
        return commodityMarketPriceMonthlyDao.selectById(id);
    }

    /**
     * 每月批量获取采购比价
     *
     * @return
     */
    @Override
    public Boolean getPriceMonthly() {
        //清空数据表
        commodityMarketPriceMonthlyDao.truncateTable();

        List<VToMsyBcd> all = vToMsyBcdService.getAll();
        List<List<VToMsyBcd>> lists = CollUtil.split(all, (all.size() + 9) / 10);
        for (List<VToMsyBcd> list : lists) {
            List<CommodityMarketPriceMonthly> priceMonthlyList = new ArrayList<>();
            for (VToMsyBcd vToMsyBcd : list) {
                BanMaHuiRequest banMaHuiRequest = new BanMaHuiRequest();
                String randomString = RandomUtil.randomString(32);
                banMaHuiRequest.setNonceStr(randomString);
                banMaHuiRequest.setAppid(BanMaHuiEnum.APP_ID.getValue());
                banMaHuiRequest.setMethod(BanMaHuiEnum.METHOD_TYPE.getValue());

                banMaHuiRequest.setVersion(BanMaHuiEnum.VERSION.getValue());
                String productId = vToMsyBcd.getBcd();
                banMaHuiRequest.setProductId(productId);
                String aCase = md5("appid=13682463&method=purchase.price.get&nonce_str=58feb19886422&product_id=6934522809831&version=1.0.0&key=e1cf0ddcf6b47b59c351565d8ad717af")
                        .toUpperCase();
                System.out.println(aCase);
                String originSign = StrUtil.format("appid={}&method={}&nonce_str={}&product_id={}&region_code={}&version={}&key={}",BanMaHuiEnum.APP_ID.getValue(),BanMaHuiEnum.METHOD_TYPE.getValue(),randomString,productId,BanMaHuiEnum.REGION_CODE.getValue(),BanMaHuiEnum.VERSION.getValue(),BanMaHuiEnum.SERCET.getValue());
                System.out.println(originSign);
                String sign=md5(originSign).toUpperCase();
                banMaHuiRequest.setSign(sign);
                String url= BanMaHuiEnum.URL.getValue();
                OkHttpClient client = new OkHttpClient();
                Map<String, Object> requestBodyMap = new HashMap<>();

                requestBodyMap.put(BanMaHuiEnum.VERSION.getCode(),banMaHuiRequest.getVersion());
                requestBodyMap.put(BanMaHuiEnum.METHOD_TYPE.getCode(), banMaHuiRequest.getMethod());
                requestBodyMap.put("sign",banMaHuiRequest.getSign());
                requestBodyMap.put(BanMaHuiEnum.APP_ID.getCode(),banMaHuiRequest.getAppid());
                requestBodyMap.put(BanMaHuiEnum.REGION_CODE.getCode(),BanMaHuiEnum.REGION_CODE.getValue());
                requestBodyMap.put("nonce_str",banMaHuiRequest.getNonceStr());
                requestBodyMap.put("product_id",banMaHuiRequest.getProductId());

                String requestBodyJsonStr = JSON.toJSONString(requestBodyMap);
//                System.out.println(requestBodyJsonStr);
                RequestBody requestBody = RequestBody.create(requestBodyJsonStr, MediaType.parse("application/json;charset=utf-8"));
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .addHeader("Content-Type","application/json")
                        .build();
                CommodityMarketPriceMonthly priceMonthly = new CommodityMarketPriceMonthly();
                try {
                    Response execute = client.newCall(request).execute();
                    if (execute.isSuccessful()) {
                        String string = execute.body().string();
//                        log.info(string);

                        priceMonthly =JSON.to(CommodityMarketPriceMonthly.class, string);
                        System.out.println(priceMonthly);
                        if (priceMonthly.getProductId()!=null){
                            priceMonthly.setCheckFlag(false);
                            priceMonthly.setCreateTime(LocalDateTime.now());
                            priceMonthly.setUpdateTime(LocalDateTime.now());
                            priceMonthlyList.add(priceMonthly);
                        }
//                        priceMonthly.setProductId(productId);
                    }


                } catch (IOException e) {
                    log.error(e.getMessage());
                    throw new RuntimeException(e);
                }
            }
            boolean b = this.saveBatch(priceMonthlyList);
            log.info(StrUtil.format("本次插入结果:{}本次一共插入数据条数为：{}",b,priceMonthlyList.size()));
        }
//        for (VToMsyBcd vToMsyBcd : all) {
//            BanMaHuiRequest banMaHuiRequest = new BanMaHuiRequest();
//            String randomString = RandomUtil.randomString(32);
//            banMaHuiRequest.setNonceStr(randomString);
//            banMaHuiRequest.setAppid(BanMaHuiEnum.APP_ID.getValue());
//            banMaHuiRequest.setMethod(BanMaHuiEnum.METHOD_TYPE.getValue());
//
//            banMaHuiRequest.setVersion(BanMaHuiEnum.VERSION.getValue());
//            String productId = vToMsyBcd.getBcd();
//            banMaHuiRequest.setProductId(productId);
//            String aCase = md5("appid=13682463&method=purchase.price.get&nonce_str=58feb19886422&product_id=6934522809831&version=1.0.0&key=e1cf0ddcf6b47b59c351565d8ad717af")
//                    .toUpperCase();
//            System.out.println(aCase);
//            String originSign = StrUtil.format("appid={}&method={}&nonce_str={}&product_id={}&region_code={}&version={}&key={}",BanMaHuiEnum.APP_ID.getValue(),BanMaHuiEnum.METHOD_TYPE.getValue(),randomString,productId,BanMaHuiEnum.REGION_CODE.getValue(),BanMaHuiEnum.VERSION.getValue(),BanMaHuiEnum.SERCET.getValue());
//            System.out.println(originSign);
//            String sign=md5(originSign).toUpperCase();
//            banMaHuiRequest.setSign(sign);
//            String url= BanMaHuiEnum.URL.getValue();
//            OkHttpClient client = new OkHttpClient();
//            Map<String, Object> requestBodyMap = new HashMap<>();
//
//            requestBodyMap.put(BanMaHuiEnum.VERSION.getCode(),banMaHuiRequest.getVersion());
//            requestBodyMap.put(BanMaHuiEnum.METHOD_TYPE.getCode(), banMaHuiRequest.getMethod());
//            requestBodyMap.put("sign",banMaHuiRequest.getSign());
//            requestBodyMap.put(BanMaHuiEnum.APP_ID.getCode(),banMaHuiRequest.getAppid());
//            requestBodyMap.put(BanMaHuiEnum.REGION_CODE.getCode(),BanMaHuiEnum.REGION_CODE.getValue());
//            requestBodyMap.put("nonce_str",banMaHuiRequest.getNonceStr());
//            requestBodyMap.put("product_id",banMaHuiRequest.getProductId());
//
//            String requestBodyJsonStr = JSON.toJSONString(requestBodyMap);
//            System.out.println(requestBodyJsonStr);
//            RequestBody requestBody = RequestBody.create(requestBodyJsonStr, MediaType.parse("application/json;charset=utf-8"));
//            Request request = new Request.Builder()
//                    .url(url)
//                    .post(requestBody)
//                    .addHeader("Content-Type","application/json")
//                    .build();
//            CommodityMarketPriceMonthly priceMonthly = new CommodityMarketPriceMonthly();
//            try {
//                Response execute = client.newCall(request).execute();
//                if (execute.isSuccessful()) {
//                    String string = execute.body().string();
//                    log.info(string);
//
//                    priceMonthly =JSON.to(CommodityMarketPriceMonthly.class, string);
//                    System.out.println(priceMonthly);
//                    priceMonthly.setProductId(productId);
//                    priceMonthlyList.add(priceMonthly);
//                }
//
//
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }

        return Boolean.TRUE;
    }


}
